package com.ja.openchat.ui.me;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.contact.ContactListAdapter;
import com.ja.openchat.views.SideIndexBar;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.message.MessageSendUser;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.DensityUtil;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class BlockedUserListActivity extends JaBaseActivity {

    @BindView(R.id.recyclerView)
    SwipeRecyclerView recyclerView;
    @BindView(R.id.slide)
    SideIndexBar slideBar;

    private ContactListAdapter contactListAdapter;
    private List<Section> sectionList = new ArrayList<>();

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    //创建侧滑菜单
    private final SwipeMenuCreator creator = (leftMenu, rightMenu, position) -> {
        Section sec = sectionList.get(position);
        if (!sec.isHeader()) {
            SwipeMenuItem delItem = new SwipeMenuItem(this)
                    .setBackgroundColorResource(R.color.red8)
                    .setImage(R.drawable.icon_close)
                    .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                    .setWidth(DensityUtil.dp2px(65));
            rightMenu.addMenuItem(delItem);
        }
    };

    public static void start(Activity activity) {
        Intent intent = new Intent();
        intent.setClass(activity, BlockedUserListActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public void initData() {
        setTitle(getString(R.string.black_list));
        //初始化列表
        initListUI();
        //加载数据
        reloadContacts(new ArrayList<>());
        reloadBlockedUsers();
        //索引事件
        slideBar.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
    }

    private void initListUI() {
        //初始化列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        //设置侧滑菜单列表
        recyclerView.setSwipeMenuCreator(creator);
        //侧滑事件监听回调
        recyclerView.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            switch (menuBridge.getPosition()) {
                case 0:
                    menuBridge.closeMenu();
                    unblockUser((UserInfo) sectionList.get(adapterPosition).getObject());
                    break;
            }
        });

        contactListAdapter = new ContactListAdapter(R.layout.adapter_contact_list, R.layout.adapter_section_contact_list, sectionList);
        contactListAdapter.setEmptyView(R.layout.status_center_empty_view);
        recyclerView.setAdapter(contactListAdapter);
    }

    private void reloadBlockedUsers() {
        TelegramManager.getTelegramManager().requestblockedUserList(this, new TgResultBlock<List<MessageSendUser>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<MessageSendUser> obj) {
                if (obj != null) {
                    List<UserInfo> list = new ArrayList<>();
                    for (MessageSendUser sendUser : obj) {
                        if (sendUser != null && sendUser.user_id > 0) {
                            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(sendUser.user_id);
                            if (user != null) {
                                list.add(user);
                            }
                        }
                    }
                    reloadContacts(list);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void reloadContacts(List<UserInfo> list) {
        sectionList.clear();
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<UserInfo>() {
                @Override
                public int compare(UserInfo u1, UserInfo u2) {
                    if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                        return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                    }
                    return 0;
                }
            });
        }
        //生成a-z hash
        Map<String, List<UserInfo>> sectionMap = new HashMap<>();
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            sectionMap.put(azIndex, new ArrayList<>());
        }
        //插入userinfo
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    sectionMap.get("#").add(user);
                }
            } else {
                sectionMap.get("#").add(user);
            }
        }
        //ui数据
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (UserInfo user : sectionMap.get(azIndex)) {
                    sectionList.add(new Section(false, user));
                }
            }
        }
        //刷新页面
        contactListAdapter.notifyDataSetChanged();
    }

    private void unblockUser(UserInfo user) {
        showProgress();
        TelegramManager.getTelegramManager().blockUser(this, user.id, false, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    reloadBlockedUsers();
                    showWarnTip(getString(R.string.removed_from_blacklist));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_blocked_user_list;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}